package com.cisdi.analysis.service.util;

import com.cisdi.analysis.common.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author liujunnan
 * @date 2018/5/23
 */
@Component
public class UploadFileUtil {

    /**
     * 操作系统环境为windows
     */
    private static final String LINUX = "linux";

    /**
     * 操作系统环境为linux
     */
    private static final String WINDOWS = "windows";

    @Autowired
    private QcloudClient qcloudClient;

    @Value("${os.identification}")
    private String osIdentification;

    @Value("${data.file.location}")
    private String dataFileLocation;

    @Value("${remote.data.url}")
    private String remoteDataUrl;

    /**
     * 获取文件类型
     * @param fileName
     * @return
     */
    private static String getFileType(String fileName) {
        int length = fileName.length();
        int point = fileName.lastIndexOf(".");
        String fileType = "";
        if (point == -1) {
            return null;
        }
        fileType = fileName.substring(point, length).toLowerCase();
        return fileType;
    }

    /**
     * 获取UUID 32位
     * @return
     */
    private static String get32UUID() {
        return UUID.randomUUID().toString().trim().replaceAll("-", "");
    }

    /**
     * 执行文件上传的
     * @param files      文件
     * @param folderPath 上传目录
     * @return 文件上传之后存储的路径的url List集合
     * @throws Exception
     */
    public Map uploadFile(MultipartFile file, String folderPath) throws Exception {
        Map<String, String> map = new HashMap(2);
        if (file != null) {
            //循环获取file数组中得文件
            String myFileName = file.getOriginalFilename();
            if (StringUtil.notEmpty(myFileName)) {
                String type = getFileType(myFileName);
                String fileName = get32UUID() + type;
                InputStream input = file.getInputStream();
                String localPath;
                String osIdentify = osIdentification;
                String location = dataFileLocation;
                //操作系统不一样获取文件路径不一样
                switch (osIdentify) {
                    case LINUX:
                        localPath = location + fileName;
                        break;
                    case WINDOWS:
                        //本地路径
                        //localPath = this.getClass().getResource("/").getPath() + "/uploadFiles/" + fileName;
                        localPath = System.getProperty("user.dir") + "/uploadFiles/" + fileName;
                        break;
                    default:
                        throw new Exception("请指定运行的环境和项目文件上传的位置！");
                }

                FileOutputStream os = new FileOutputStream(localPath);
                byte[] buffer = new byte[1024];
                int n = 0;
                //写到本地
                while (-1 != (n = input.read(buffer))) {
                    os.write(buffer, 0, n);
                }
                os.flush();
                os.close();
                input.close();
                //执行文件上传云端
                String result = qcloudClient.uploadFile(folderPath, localPath);
                //删除上传之后的文件可以删除上传后的文件
                //File fileLocal = new File(localPath);
                //fileLocal.delete();
                map.put("local_file", localPath);
                //这个用于测试的时候将信息返回给前端界面的,实际使用的时候可以去掉
                map.put("result", remoteDataUrl + fileName);
                map.put("original_name", myFileName);
            }
        }
        return map;
    }
}